package com.ibm.crl.sb.thread.czbk;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 
 * @author Super尚
 * 
 * 
 *         自定义缓冲池
 */
public class CacheDemo {

	private Map<String, Object> cache = new HashMap<String, Object>();
	private ReadWriteLock lock = new ReentrantReadWriteLock();

	public static void main(String[] args) {
		new CacheDemo();
	}

	public Object getValue(String key) {
		Object obj = cache.get(key);
		if (obj == null) {
			// obj = getSql();
		}
		return obj;
	}

	public synchronized Object getValue1(String key) {
		Object obj = cache.get(key);
		if (obj == null) {
			// obj = getSql();
		}
		return obj;
	}

	public Object getValue2(String key) {
		lock.readLock().lock();
		Object obj = null;
		try {
			obj = cache.get(key);
			if (obj == null) {
				lock.readLock().unlock();
				lock.writeLock().lock();
				try {
					// obj = getSql();
				} finally {
					lock.writeLock().unlock();
				}
				lock.readLock().lock();
			}
		} finally {
			lock.readLock().unlock();
		}
		return obj;
	}

	volatile boolean cacheValid;
	final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

	/**
	 * 
	 * 
	 * 
	 * @return
	 * 
	 *         精髓
	 * 
	 */

	public Object getValue3() {
		rwl.readLock().lock();
		if (!cacheValid) {
			// Must release read lock before acquiring write lock
			rwl.readLock().unlock();
			rwl.writeLock().lock();
			try {
				// Recheck state because another thread might have
				// acquired write lock and changed state before we did.
				if (!cacheValid) {
					// data = ...
					cacheValid = true;
				}
				// Downgrade by acquiring read lock before releasing write lock
				rwl.readLock().lock();
			} finally {
				rwl.writeLock().unlock(); // Unlock write, still hold read
			}
		}

		try {
			// use(data);
		} finally {
			rwl.readLock().unlock();
		}
		return null;
	}

}
